package com.example.managemyself.ui.meditation;

import android.app.AlertDialog;
import android.content.Context;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.managemyself.R;
import java.util.Locale;

/**
 * 冥想功能帮助类
 * 提供冥想计时器功能
 */
public class MeditationHelper {
    
    /**
     * 显示冥想对话框
     */
    public static void showMeditationDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_meditation, null);
        builder.setView(dialogView);
        
        AlertDialog dialog = builder.create();
        
        // 初始化视图
        TextView tvTimer = dialogView.findViewById(R.id.tvTimer);
        Button btnStart = dialogView.findViewById(R.id.btnStart);
        Button btnPause = dialogView.findViewById(R.id.btnPause);
        Button btnReset = dialogView.findViewById(R.id.btnReset);
        SeekBar seekBarDuration = dialogView.findViewById(R.id.seekBarDuration);
        TextView tvDuration = dialogView.findViewById(R.id.tvDuration);
        Button btnWhiteNoise = dialogView.findViewById(R.id.btnWhiteNoise);
        
        // 冥想计时器管理器
        MeditationTimerManager timerManager = new MeditationTimerManager(tvTimer, btnStart, btnPause, btnReset);
        
        // 设置时长选择器
        setupDurationSeekBar(seekBarDuration, tvDuration, timerManager);
        
        // 设置按钮事件
        btnStart.setOnClickListener(v -> timerManager.startTimer());
        btnPause.setOnClickListener(v -> timerManager.pauseTimer());
        btnReset.setOnClickListener(v -> timerManager.resetTimer());
        
        if (btnWhiteNoise != null) {
            btnWhiteNoise.setOnClickListener(v -> showWhiteNoiseSelector(context));
        }
        
        // 设置对话框关闭事件
        dialog.setOnDismissListener(dialogInterface -> {
            timerManager.cleanup();
        });
        
        dialog.show();
    }
    
    /**
     * 设置时长选择器
     */
    private static void setupDurationSeekBar(SeekBar seekBar, TextView tvDuration, MeditationTimerManager timerManager) {
        seekBar.setMax(60); // 最大60分钟
        seekBar.setProgress(10); // 默认10分钟
        tvDuration.setText("10分钟");
        timerManager.setDurationMinutes(10);
        
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int minutes = Math.max(1, progress); // 最少1分钟
                    tvDuration.setText(minutes + "分钟");
                    timerManager.setDurationMinutes(minutes);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    /**
     * 显示白噪音选择器
     */
    private static void showWhiteNoiseSelector(Context context) {
        String[] noiseNames = {"关闭白噪音", "雨声", "海浪声", "森林声", "风声", "篝火声"};
        
        new AlertDialog.Builder(context)
                .setTitle("选择白噪音")
                .setItems(noiseNames, (dialog, which) -> {
                    if (which == 0) {
                        Toast.makeText(context, "白噪音已关闭", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, "正在播放: " + noiseNames[which] + "（模拟）", Toast.LENGTH_SHORT).show();
                    }
                })
                .show();
    }
    
    /**
     * 冥想计时器管理器
     */
    private static class MeditationTimerManager {
        private TextView tvTimer;
        private Button btnStart, btnPause, btnReset;
        private CountDownTimer timer;
        private long timeLeftInMillis;
        private long totalTimeInMillis;
        private boolean isRunning = false;
        
        public MeditationTimerManager(TextView tvTimer, Button btnStart, Button btnPause, Button btnReset) {
            this.tvTimer = tvTimer;
            this.btnStart = btnStart;
            this.btnPause = btnPause;
            this.btnReset = btnReset;
        }
        
        public void setDurationMinutes(int minutes) {
            if (!isRunning) {
                totalTimeInMillis = minutes * 60 * 1000L;
                timeLeftInMillis = totalTimeInMillis;
                updateTimerDisplay();
            }
        }
        
        public void startTimer() {
            if (timeLeftInMillis <= 0) {
                return;
            }
            
            timer = new CountDownTimer(timeLeftInMillis, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    timeLeftInMillis = millisUntilFinished;
                    updateTimerDisplay();
                }
                
                @Override
                public void onFinish() {
                    timeLeftInMillis = 0;
                    isRunning = false;
                    updateTimerDisplay();
                    updateButtonStates();
                    
                    // 冥想完成提示
                    Toast.makeText(tvTimer.getContext(), "冥想完成！感谢您的坚持。", Toast.LENGTH_LONG).show();
                }
            }.start();
            
            isRunning = true;
            updateButtonStates();
        }
        
        public void pauseTimer() {
            if (timer != null) {
                timer.cancel();
            }
            isRunning = false;
            updateButtonStates();
        }
        
        public void resetTimer() {
            if (timer != null) {
                timer.cancel();
            }
            timeLeftInMillis = totalTimeInMillis;
            isRunning = false;
            updateTimerDisplay();
            updateButtonStates();
        }
        
        private void updateTimerDisplay() {
            int minutes = (int) (timeLeftInMillis / 1000) / 60;
            int seconds = (int) (timeLeftInMillis / 1000) % 60;
            String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
            tvTimer.setText(timeFormatted);
        }
        
        private void updateButtonStates() {
            btnStart.setEnabled(!isRunning && timeLeftInMillis > 0);
            btnPause.setEnabled(isRunning);
            btnReset.setEnabled(!isRunning && timeLeftInMillis != totalTimeInMillis);
        }
        
        public void cleanup() {
            if (timer != null) {
                timer.cancel();
            }
        }
    }
} 